﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Printing;
using System.Collections;

namespace Turtle8
{
    public partial class LibaryPanel : UserControl
    {
        Stack<string> pathStack = new Stack<string>();
        ExtendedTreeNode treeSource = new ExtendedTreeNode("ספריה ראשית", ExtendedTreeNode.FileSystemEntryType.Directory);

        public LibaryPanel()
        {
            InitializeComponent();
            this.Dock = DockStyle.Fill;

            treeView.Nodes.Add(treeSource);
            FillTreeView(treeSource);
            treeSource.Expand();
        }

        /// <summary>
        /// fills the treeView items from startpath/ספריה ראשית
        /// </summary>
        /// <param name="parent"></param>
        private void FillTreeView(TreeNode parent)
        {
            try
            {
                DirectoryInfo dirInfo;
                if (parent.Equals(treeSource))
                    dirInfo = new DirectoryInfo(CompanyManager.StartupPath + @"\" + parent.Text);
                else dirInfo = new DirectoryInfo(CompanyManager.StartupPath + @"\" + parent.FullPath);

                if (!dirInfo.Exists)
                    throw new DirectoryNotFoundException("directory does not exist:" + parent.Text);

                //adds directories to the current directory TreeNode. recursive calls.
                foreach (DirectoryInfo di in dirInfo.GetDirectories())
                {
                    ExtendedTreeNode child = new ExtendedTreeNode(di.Name, ExtendedTreeNode.FileSystemEntryType.Directory);
                    parent.Nodes.Add(child);
    
                    FillTreeView(child);
                }

                //adds files to the current directory TreeNode
                foreach (FileInfo fi in dirInfo.GetFiles())
                {
                    ExtendedTreeNode child = new ExtendedTreeNode(fi.Name, ExtendedTreeNode.FileSystemEntryType.File);
                    parent.Nodes.Add(child);
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }

        /// <summary>
        /// add new directory to the treeView and to the fileSystem.
        /// </summary>
        private void addNewDirectory()
        {
            ExtendedTreeNode currentNode = (ExtendedTreeNode)treeView.SelectedNode;
            if (currentNode == null)
                currentNode = treeSource;
            else if (currentNode.FSType == ExtendedTreeNode.FileSystemEntryType.File)
                currentNode = (ExtendedTreeNode)currentNode.Parent;

            bool isNewDir = false;
            foreach (TreeNode node in currentNode.Nodes)
                if (node.Text.StartsWith("ספריה חדשה"))
                {
                    isNewDir = true;
                    break;
                }

            ExtendedTreeNode newNode;
            if (!isNewDir)
                newNode = new ExtendedTreeNode("ספריה חדשה", ExtendedTreeNode.FileSystemEntryType.Directory);
            else
            {
                int i = 1;
                while (true)
                {
                    string str = CompanyManager.StartupPath + @"\" + currentNode.FullPath + @"\ספריה חדשה - " + i.ToString();
                    if (!Directory.Exists(str))
                        break;
                    else i++;
                }

                newNode = new ExtendedTreeNode("ספריה חדשה - " + i.ToString(), ExtendedTreeNode.FileSystemEntryType.Directory);
            }

            currentNode.Nodes.Add(newNode);
            string newDirPath = CompanyManager.StartupPath + @"\" + newNode.FullPath;
            Directory.CreateDirectory(newDirPath); 
        }

        /// <summary>
        /// handles a renmae in the tree view. renames the correspondent file in the fileSystem.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            ExtendedTreeNode node = (ExtendedTreeNode)e.Node;
            try
            {
                if (node.FSType == ExtendedTreeNode.FileSystemEntryType.Directory)
                    Directory.Move(CompanyManager.StartupPath + @"\" + e.Node.FullPath, CompanyManager.StartupPath + @"\" + node.Parent.FullPath + @"\" + e.Label);
                else File.Move(CompanyManager.StartupPath + @"\" + e.Node.FullPath, CompanyManager.StartupPath + @"\" + node.Parent.FullPath + @"\" + e.Label);
            }
            catch (Exception)
            {
                e.CancelEdit = true;
            }
        }

        private void load()
        {
            ExtendedTreeNode currentNode = (ExtendedTreeNode)treeView.SelectedNode;
            if (currentNode == null)
                currentNode = treeSource;
            else if (currentNode.FSType == ExtendedTreeNode.FileSystemEntryType.File)
                currentNode = (ExtendedTreeNode)currentNode.Parent;

            OpenFileDialog dlg = new OpenFileDialog();

            dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            dlg.Title = "...בחר קובץ";

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                ExtendedTreeNode child = new ExtendedTreeNode(dlg.SafeFileName, ExtendedTreeNode.FileSystemEntryType.File);
                currentNode.Nodes.Add(child);
                File.Copy(dlg.FileName, CompanyManager.StartupPath + @"\" + child.FullPath);
            }
        }

        private void delete()
        {
            ExtendedTreeNode currentNode = (ExtendedTreeNode)treeView.SelectedNode;

            //we won't allow to delete the source node.
            if (!currentNode.Equals(treeSource))
                try
                {
                    if (currentNode.FSType.Equals(ExtendedTreeNode.FileSystemEntryType.File))
                    {
                        File.Delete(CompanyManager.StartupPath + @"\" + currentNode.FullPath);
                        currentNode.Remove();
                    }
                    else 
                    {
                        if (currentNode.Nodes.Count != 0)
                        {
                            DialogResult result = MessageBox.Show("?האם אתה בטוח שברצונך למחוק את הספריה", "!שים לב", MessageBoxButtons.YesNo);
                            if (result == DialogResult.Yes)
                            {
                                Directory.Delete(CompanyManager.StartupPath + @"\" + currentNode.FullPath, true);
                                currentNode.Remove();
                            }
                        }
                        else
                        {
                            Directory.Delete(CompanyManager.StartupPath + @"\" + currentNode.FullPath);
                            currentNode.Remove();
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
        }

        
        //contextMenu handlers
        private void ToolStripMenuItem_NewFolder_Click(object sender, EventArgs e)
        { addNewDirectory(); }
        private void ToolStripMenuItem_Delete_Click(object sender, EventArgs e)
        { delete(); }
        private void ToolStripMenuItem1_Upload_Click(object sender, EventArgs e)
        { load(); }

        //toolStrip handlers
        private void toolStripButtonNewFolder_Click(object sender, EventArgs e)
        { addNewDirectory(); }
        private void toolStripButtonDelete_Click(object sender, EventArgs e)
        { delete(); }
        private void toolStripButtonLoad_Click(object sender, EventArgs e)
        { load(); }

        private void treeView_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (Char)Keys.Delete)
                delete();
        }

        private void treeView_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F2)
                treeView.SelectedNode.BeginEdit();
            else if (e.KeyCode == Keys.Delete)
                delete();
        }

        private void treeView_DoubleClick(object sender, EventArgs e)
        {
            ExtendedTreeNode node = (ExtendedTreeNode)treeView.SelectedNode;
            if (node != null && node.FSType == ExtendedTreeNode.FileSystemEntryType.File)
                System.Diagnostics.Process.Start(CompanyManager.StartupPath + @"\" + node.FullPath);
        }

        private void treeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode currentNode = treeView.SelectedNode;
            textBox.Text = currentNode.FullPath;
        }    
 
    }


    class ExtendedTreeNode : TreeNode
    {
        public enum FileSystemEntryType { File, Directory }
        public FileSystemEntryType FSType
        { get; set; }

        public ExtendedTreeNode(string label, FileSystemEntryType type)
            : base(label)
        { FSType = type; }
    }
}
